package com.atguigu.map;

public class LinkedListMap<K,V> implements Map<K,V> {

    private class Node{
        K key;
        V value;
        Node next;
        public Node(K key,V value,Node next){
            this.key=key;
            this.value=value;
            this.next=next;
        }
        public Node(K key,V value){
            this(key,value,null);
        }
        public Node(){
            this(null,null,null);
        }

        @Override
        public String toString() {
            return "{"+key.toString()+" : "+value.toString()+"}";
        }
    }
    private Node dummyHead;
    private int size;
    public LinkedListMap(){
        this.dummyHead=new Node();
        this.size=0;
    }
    private Node getNode(K key){
        Node cur=dummyHead.next;
        while(cur!=null){
            if(cur.key.equals(key)){
                return cur;
            }
            cur=cur.next;
        }
        return null;
    }

    @Override
    public void add(K key, V value) {
        Node node=getNode(key);
        if(node==null){
            dummyHead.next=new Node(key,value,dummyHead.next);
            size++;
        }else{
            node.value=value;
        }
    }

    @Override
    public V remove(K key) {
        Node node=dummyHead;
        V res=null;
        while(node.next!=null){
            if(node.next.key.equals(key)){
                Node delNode=node.next;
                node.next=delNode.next;
                delNode.next=null;
                size--;
                res=delNode.value;
            }
            node=node.next;
        }
        return res;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key)!=null;
    }

    @Override
    public V get(K key) {
        Node cur=getNode(key);
        if(cur!=null){
            return cur.value;
        }
        return null;
    }

    @Override
    public void set(K key, V newValue) {
        Node node=getNode(key);
        if(node==null){
            throw new IllegalArgumentException(key+"does't exist!");
        }
        node.value=newValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public String toString() {
        StringBuilder res=new StringBuilder();
        Node preNode=dummyHead.next;
        res.append("{");
        while(preNode!=null){
            res.append(preNode);
            preNode=preNode.next;
        }
        return res.append("}").toString();
    }
}
